import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

// This class will get called during the log in.
// This class will see if the user exists already or, wrong password or correct log in.
public class LogInPage extends HttpServlet{

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/plain");
		PrintWriter pw = response.getWriter();
		String userId = request.getParameter("userId");
		String password = request.getParameter("password");
		
		//connect to the database
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		int result = 0;
		String query = "SELECT * from user";
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			con = DriverManager.getConnection("jdbc:mysql://bungle08.cs.toronto.edu:3306/group22",
			"group22", "123456");
			if(!con.isClosed()){
				stmt = con.createStatement();		
				rs = stmt.executeQuery(query);
					
					
				while (rs.next()) {
	
					if(userId.equals(rs.getString("id"))){
						if(password.equals(rs.getString("password"))){
						// Valid log in	
							pw.println("1");
							result = 1;
							break;
						}else{
						//wrong password
							pw.println("2");
							result =1;
							break;
							
						}
					}
				}
				if (result==0){
				// Not existing user
					pw.println("0");
				}
			}
		}
		catch(Exception e) {
			pw.println("Exception: " + e.getMessage());
		} finally {
			try {
				if(con != null)
					con.close();
			} catch(SQLException e) {}
		}}
}
						